from flask import request
import logging
from functools import wraps
from flask import session
from sale.utils import app
import json


logger = logging.getLogger(__name__)


def logit(func):

    @wraps
    def wrapper(*args, **kw):
        if request.method == 'GET':
            logger.info("requst data: %s", request.args)
        if request.method == 'POST':
            logger.info("request data: %s", request.form)
        return func(*args, **kw)
    return wrapper


@app.before_request
def logging_print():
    if request.method == 'GET':
        logger.info("requst data: %s", request.args)
    if request.method == 'POST':
        logger.info("request data: %s", request.form)


@app.after_request
def logging_print(rsp):
    logger.info('data: %s, status: %s, headers: %s', rsp.data, rsp.status_code, rsp.headers)
    return rsp


@app.after_request
def amend_user_info(rsp):
    rsp_data = rsp.json
    if rsp_data.get('name'):
        rsp_data['name'] = '111111111'
        data = json.dumps(rsp_data)
        rsp.data = data.encode('utf-8')
    return rsp


def auth(func):

    @wraps(func)
    def wrapper(*args, **kw):
        token = request.cookies.get('token')
        user_info = session.get(token)
        if not user_info:
            return {'msg': '请重新登录', 'code': 'auth_fail'}
        request.user_info_view = user_info
        return func(*args, **kw)
    return wrapper


